package cn.com.callback

import groovy.json.*;
import groovy.swing.impl.DefaultAction
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.crypto.Cipher
import javax.crypto.SecretKey
import javax.crypto.spec.SecretKeySpec
import javax.servlet.RequestDispatcher;
import cn.com.callback.CallBackInvoke
import cn.com.callback.ServiceBackInvoke
import cn.com.elite.EliteBean;
import cn.com.elite.Util;
import java.security.MessageDigest;
import java.sql.ResultSet;
import java.text.ParseException
import java.text.SimpleDateFormat;
import java.time.Instant

import org.apache.commons.codec.binary.Base64
import org.apache.commons.codec.digest.DigestUtils
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import org.json.JSONArray
import org.json.JSONException
import org.json.JSONObject
import cn.com.kh.hst.ThreeDesUtil
import cn.com.kh.KHUtil;
import cn.com.kh.getProperty;


/**
 *
 * @Title: aipHSTOldCustNoAttribution
 * @Description:华盛证券 客户服务顾问未分配历史数据 --内部接口
 * @author: chieh
 * @date 2021-11-29 15:00:00
 *
 */

public class aipHSTOldCustNoAttribution implements ServiceBackInvoke {
	private static final Log log = LogFactory.getLog(aipHSTOldCustNoAttribution.class);

	public String doCallBack(EliteBean eliteBean, HttpServletRequest request, HttpServletResponse response) {

		response.setCharacterEncoding("UTF-8");
		response.setHeader("Access-Control-Allow-Origin", "*");
		String getMethod = request.getMethod();
		log.debug("getMethod:" + getMethod);

		String inData = "";
		String outData = "";
		String totalData = "";
		String dataSourceID = "dataSource";


		BufferedReader iny = null;
		if (getMethod.equals("GET")) {
			inData = request.getParameter("data");
			log.debug("原始Get请求参数:" + inData);
		} else {
			InputStreamReader reader = new InputStreamReader(request.getInputStream(), "UTF-8");
			iny = new BufferedReader(reader);
			String line;
			while ((line = iny.readLine()) != null) {
				inData += line;
			}
			log.debug("原始Post请求参数:" + inData);
		}

		inData = URLDecoder.decode(inData, "UTF-8");
		log.debug("原始inData URLDecoder:" + inData);

		try {

			long startTime = System.currentTimeMillis();
			String reJson = null;
			long endTime = 0;
			JSONObject inObject = new JSONObject(inData);
			//鉴权变量
			String appid = getProperty.get("appid");
			String appsecret = getProperty.get("appsecret");

			//sign加密前后
			String signfront = "";
			String signafter = "";
			
			def updateBeginTime = GetJV(inObject, "updateBeginTime");
			def updateEndTime = GetJV(inObject, "updateEndTime");
			if(updateBeginTime=='' || updateEndTime=='') {
				def selectime=eliteBean.chaxun_sql("SELECT DATE_FORMAT( DATE_SUB(CURDATE(), INTERVAL 1 DAY), '%Y-%m-%d 00:00:00') AS starttime,DATE_FORMAT(NOW(),'%Y-%m-%d 23:59:59') AS endtime","dataSource");
				for (int i = 0; i < selectime.size(); i++) {
					updateBeginTime = selectime.get(i).get("starttime");
					updateEndTime = selectime.get(i).get("endtime");
				}
				log.debug("当前时间1：" +updateBeginTime);
				log.debug("当前时间2：" +updateEndTime);
				log.debug("当前时间3：" +selectime);
			}
			String sign_time=Instant.now().getEpochSecond();
			log.debug("解析信息-" +  "sign_time: " + sign_time);

			def pageNo = "1";
			def pageSize = "50";

			HashMap<String, String> paramHashMap = new HashMap<String, String>() {
				{
					put("sign_time", sign_time);
					put("pageNo", pageNo);
					put("pageSize", pageSize);
					put("openBeginTime", updateBeginTime);
					put("openEndTime", updateEndTime);
				}
			};

			log.debug("paramHashMap：" + paramHashMap);
			//自然排序 升序参数
			signfront= ThreeDesUtil.sortMap(paramHashMap,appid,appsecret);
			log.debug("sign加密MD5前：" + signfront);
			signafter = Util.getMD5Str(signfront);
			log.debug("sign加密MD5后：" + signafter);

			//拼接接口入参
			paramHashMap.put("client_key", appid);
			paramHashMap.put("sign", signafter);

			String injson=ThreeDesUtil.SplicingMap(paramHashMap,"&");
			log.debug("injson:" + injson);

			totalData = Querypromocode(eliteBean, injson,dataSourceID);
			//解析SSO返回信息
			JSONObject jsonObject = new JSONObject(totalData);
			String total = GetJV(jsonObject, "message");
			log.debug("total:" + total);
			double number=Integer.parseInt(total)/Integer.parseInt(pageSize);
			log.debug("number :" + number);
			int count=Math.ceil(number);
			log.debug("count :" + count);

			for (int i = 0; i <=count; i++) {
				//华盛接口连续调用可能异常 添加2S睡眠
				Thread.sleep(60 * 1000);
				pageNo=String.valueOf(i);
				log.debug("pageNo :" + pageNo);
				sign_time=Instant.now().getEpochSecond();
				HashMap<String, String> paramHashMap1 = new HashMap<String, String>() {
					{
						put("sign_time", sign_time);
						put("pageNo", pageNo);
						put("pageSize", pageSize);
						put("openBeginTime", updateBeginTime);//更新字段开始时间
						put("openEndTime", updateEndTime);//更新字段结束时间
					}
				};

				log.debug("paramHashMap1：" + paramHashMap1);
				//自然排序 升序参数
				signfront= ThreeDesUtil.sortMap(paramHashMap1,appid,appsecret);
				log.debug("sign加密MD5前：" + signfront);
				signafter = Util.getMD5Str(signfront);
				log.debug("sign加密MD5后：" + signafter);

				//拼接接口入参
				paramHashMap1.put("client_key", appid);
				paramHashMap1.put("sign", signafter);

				String injson1=ThreeDesUtil.SplicingMap(paramHashMap1,"&");
				log.debug("injson1:" + injson1);

				Querypromocode(eliteBean, injson1,dataSourceID);
			}
			outData = "{\"result\":\"1\",\"message\":\"处理成功\",\"data\":[]}";


		} catch (Exception e) {
			log.error("接口处理异常" + e.getMessage());
			// 失败返回
			outData = "{\"result\":\"-1\",\"message\":\"处理失败(" + e.getMessage() + ")\",\"data\":[]}";
		}

		return outData;
	}

	//
	public static String Querypromocode(EliteBean eliteBean , String injson, String dataSourceID) {

		long startTime = System.currentTimeMillis();
		log.debug("处理开始时间:" + startTime);

		long endTime = System.currentTimeMillis();

		String reJson = null;
		try {

			String doURL = getProperty.get("HSTURL");
			doURL = doURL+"/ae/query-unassigned-history";
			log.debug("doURL:" + doURL);
			Map<String, String> headMap = new HashMap<String, String>();
			headMap.put("Content-Type", "application/x-www-form-urlencoded");
			def getResult = Util.doHttpPostUseHead(doURL, injson, "UTF-8", 60000, 0, headMap);
			log.debug("getResult:" + getResult);
			UUID uuid = UUID.randomUUID();

			//解析SSO返回信息
			JSONObject jsonObject = new JSONObject(getResult);
			String code = GetJV(jsonObject, "code");
			String result = GetJV(jsonObject, "result");
			JSONObject dataObject;

			log.debug("code:" + code);
			if(code == "00000") {
				dataObject = new JSONObject(result);
				String rows = GetJV(dataObject, "rows");
				String total = GetJV(dataObject, "total");
				log.debug('rows'+rows);
				log.debug('total'+total);

				SimpleDateFormat dateformat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
				String dateStr = dateformat.format(System.currentTimeMillis());

				JSONArray arrJsonArray = new JSONArray(rows);
				int arrInt = arrJsonArray.length();
				for (int i = 0; i < arrInt; i++) {
					JSONObject arrSmsJson = arrJsonArray.getJSONObject(i);
					
					String HsNo =GetJV(arrSmsJson,"hsNo");//华盛号
					String accountExecutiveId=GetJV(arrSmsJson,"accountExecutiveId");//服务顾问ID
					String tradePermission =GetJV(arrSmsJson,"tradePermission");//开通账号
					String  registerChannelId =GetJV(arrSmsJson,"registerChannelId");//注册渠道
					String registerTime =GetJV(arrSmsJson,"registerTime");//注册时间
					String openTime =GetJV(arrSmsJson,"openTime");//开户时间

					//log.debug(HsNo + ":HsNo");
					//log.debug(accountExecutiveId + ":accountExecutiveId");
					
					String Temp_Guid = KHUtil.getRandomString(31).toUpperCase();
					String Customer_Guid = "CUST_" + Temp_Guid;
					String Objective_Guid = "OBJE_" + Temp_Guid;
					String EliteTask_Guid = "TASK_" + Temp_Guid;
			
					def dataresult = eliteBean.update(
						"insert into oldcustomernoattribution (customer_guid, HsNo, accountExecutiveId, tradePermission, registerChannelId, registerTime, openTime, createtime) VALUES ('"+Customer_Guid+"','"+HsNo+"','"+accountExecutiveId+"','"+tradePermission+"','"+registerChannelId+"','"+registerTime+"','"+openTime+"',now())", "dataSource");
					
					// 查询名单是否已经存在
					List custCountList = eliteBean.chaxun_sql("Select Customer_Guid From Customer Where Customer_Id = '" + HsNo + "'", "dataSource");
					def r_Staff_Id,r_Rolegroup_Id='';
					if (custCountList.size() <= 0) {
						/*
						def staffresultsql = eliteBean.chaxun_sql("Select STAFF_ID,DEFAULTROLEGROUP From staff Where counselor_id = '" + accountExecutiveId + "'", "dataSource");
						if (staffresultsql.size() > 0) {
							Map staffMap = staffresultsql.get(0);
							r_Staff_Id = staffMap.get("STAFF_ID");
							r_Rolegroup_Id = staffMap.get("DEFAULTROLEGROUP");
						}else{
							log.debug("[进入未分配池]");
						}
						*/
						//log.debug("[分配池输出获取] 下发人:" + r_Staff_Id + " 下发组:" + r_Rolegroup_Id);
						log.debug("[进入未分配池]");
						
						 String[] custTaskDealSQL = new String[3];
						// 插入Customer表
						custTaskDealSQL[0] = "Insert Into Customer" +
								"  (Customer_Guid," +
								"   Customer_Id," +
								"   STRINGFIELD3," +
								"   sq_9," +
								"   STRINGFIELD7," +
								"   STRINGFIELD8," +

								"   Createdby," +
								"   Createddate)" +
								"  Select '" + Customer_Guid + "'," +
								"         HsNo," +
								"         tradePermission," +
								"         registerChannelId," +
								"         registerTime," +
								"         openTime," +
								"         'SELITE'," +
								"         DATE_SUB(CURDATE(), INTERVAL 30 DAY) " +
								"    From oldcustomernoattribution" +
								"   Where HsNo = '"+HsNo+"'"

						// 插入Objective表
						custTaskDealSQL[1] = "Insert Into Objective" +
								"  (Objective_Guid," +
								"   Objectivetype_Id," +
								"   Handleby_Id," +
								"   Handlegroup_Id," +
								"   Priority_Id," +
								"   Expireddate," +
								"   Customer_Guid," +
								"   Objectivestatus," +
								"   Iscontact," +
								"   Trytimes," +
								"   Successfulcontacttimes," +
								"   Createdby," +
								"   Createddate," +
								"   Obstatus," +
								"   Failure_Attempt," +
								"   Contact_Customer_Guid," +
								"   Passflag," +
								"   Lastassigndate," +
								"   Failstatus," +
								"   Successstatus," +
								"   Owner," +
								"   Workorderframe_Id," +
								"   Category," +
								"   Forecastdate," +
								"   Workorderid," +
								"   Workordertype1," +
								"   Workordertype2," +
								"   Workordertype3," +
								"   Workordertype4," +
								"   Objectivesubstatus," +
								"   Map_Id," +
								"   Curstep_Id_Map," +
								"   Max_Attempt," +
								"   Nocontacttry," +
								"   Allocation_Pool," +
								"   Appointment)" +
								"Values" +
								"  ('" + Objective_Guid + "'," +
								"   'RE0TX1'," +
								"   '" + r_Staff_Id + "'," +
								"   '" + r_Rolegroup_Id + "'," +
								"   'NORMAL'," +
								"   Date_Add(Now(), Interval 1 Day)," +
								"   '" + Customer_Guid + "'," +
								"   'OPEN'," +
								"   0," +
								"   0," +
								"   0," +
								"   'SELITE'," +
								"   Now()," +
								"   'OPEN'," +
								"   999," +
								"   ''," +
								"   0," +
								"   Null," +
								"   '0'," +
								"   '0'," +
								"   ''," +
								"   'MY48ZX'," +
								"   'CASE'," +
								"   '2021-04-25 17:59:35'," +
								"   Concat('HS', Date_Format(Now(), '%Y%m%d%H'), '-', Lpad(Floor(Rand() * 10000), 4, '0'))," +
								"   'QL800E'," +
								"   'O7JIUV'," +
								"   ''," +
								"   ''," +
								"   'OPEN'," +
								"   'MY48ZX'," +
								"   'ONA0KD'," +
								"   0," +
								"   0," +
								"   0," +
								"   0)";

						// 插入EliteTask表
						custTaskDealSQL[2] = "Insert Into Elitetask" +
								"  (Elitetask_Guid," +
								"   Objective_Guid," +
								"   Objectivetype_Id," +
								"   Expectstarttime," +
								"   Expectendtime," +
								"   Obstatus," +
								"   Recordstatus," +
								"   Attempt," +
								"   Max_Attempt," +
								"   Handleby_Id," +
								"   Handlegroup_Id," +
								"   Createdby," +
								"   Createddate," +
								"   Failure_Attempt," +
								"   Comments," +
								"   Customer_Guid," +
								"   Localtrycount," +
								"   Lastassigndate," +
								"   Workorderframe_Id," +
								"   Curstepstatus," +
								"   Curstep_Id," +
								"   Stepforecastdate," +
								"   Curstep_Id_Map," +
								"   Map_Id," +
								"   Objectivesubstatus," +
								"   Elitetaskstatus," +
								"   Obflag,Maintaskstep_Id_Map)" +
								"Values" +
								"  ('" + EliteTask_Guid + "'," +
								"   '" + Objective_Guid + "'," +
								"   'RE0TX1'," +
								"   Now()," +
								"   Date_Add(Now(), Interval 3 Day)," +
								"   'OPEN'," +
								"   0," +
								"   1," +
								"   999," +
								"   '" + r_Staff_Id + "'," +
								"   '" + r_Rolegroup_Id + "'," +
								"   'SELITE'," +
								"   Now()," +
								"   999," +
								"   ''," +
								"   '" + Customer_Guid + "'," +
								"   0," +
								"   Now()," +
								"   ''," +
								"   'OPEN'," +
								"   'ONA0KD'," +
								"   Now()," +
								"   'ONA0KD'," +
								"   'MY48ZX'," +
								"   'OPEN'," +
								"   'OPEN'," +
								"   1,'ONA0KD')";
								
								int[] batchSQLResult = eliteBean.updateBatch(custTaskDealSQL, "dataSource");
								log.debug("老客户入库批量处理SQL返回结果："+batchSQLResult.toString());
								
							}
							List objCountList = eliteBean.chaxun_sql("select objective_guid from objective o left join Customer c on o.customer_guid=c.customer_guid where 1=1 and o.MAP_ID='MY48ZX' and  c.Customer_Id = '" + HsNo + "'", "dataSource");
							if(custCountList.size() >= 0&&objCountList.size() <= 0) {
								def customer_guid = custCountList.get(0).get("customer_guid");
								log.debug("objective没有，但是存在customer_guid："+customer_guid);
								String[] custTaskDealSQL1 = new String[2];
								
								// 插入Objective表
								custTaskDealSQL1[0] = "Insert Into Objective" +
										"  (Objective_Guid," +
										"   Objectivetype_Id," +
										"   Handleby_Id," +
										"   Handlegroup_Id," +
										"   Priority_Id," +
										"   Expireddate," +
										"   Customer_Guid," +
										"   Objectivestatus," +
										"   Iscontact," +
										"   Trytimes," +
										"   Successfulcontacttimes," +
										"   Createdby," +
										"   Createddate," +
										"   Obstatus," +
										"   Failure_Attempt," +
										"   Contact_Customer_Guid," +
										"   Passflag," +
										"   Lastassigndate," +
										"   Failstatus," +
										"   Successstatus," +
										"   Owner," +
										"   Workorderframe_Id," +
										"   Category," +
										"   Forecastdate," +
										"   Workorderid," +
										"   Workordertype1," +
										"   Workordertype2," +
										"   Workordertype3," +
										"   Workordertype4," +
										"   Objectivesubstatus," +
										"   Map_Id," +
										"   Curstep_Id_Map," +
										"   Max_Attempt," +
										"   Nocontacttry," +
										"   Allocation_Pool," +
										"   Appointment)" +
										"Values" +
										"  ('" + Objective_Guid + "'," +
										"   'RE0TX1'," +
										"   '" + r_Staff_Id + "'," +
										"   '" + r_Rolegroup_Id + "'," +
										"   'NORMAL'," +
										"   Date_Add(Now(), Interval 1 Day)," +
										"   '" + Customer_Guid + "'," +
										"   'OPEN'," +
										"   0," +
										"   0," +
										"   0," +
										"   'SELITE'," +
										"   Now()," +
										"   'OPEN'," +
										"   999," +
										"   ''," +
										"   0," +
										"   Null," +
										"   '0'," +
										"   '0'," +
										"   ''," +
										"   'MY48ZX'," +
										"   'CASE'," +
										"   '2021-04-25 17:59:35'," +
										"   Concat('HS', Date_Format(Now(), '%Y%m%d%H'), '-', Lpad(Floor(Rand() * 10000), 4, '0'))," +
										"   'QL800E'," +
										"   'O7JIUV'," +
										"   ''," +
										"   ''," +
										"   'OPEN'," +
										"   'MY48ZX'," +
										"   'ONA0KD'," +
										"   0," +
										"   0," +
										"   0," +
										"   0)";

								// 插入EliteTask表
								custTaskDealSQL1[1] = "Insert Into Elitetask" +
										"  (Elitetask_Guid," +
										"   Objective_Guid," +
										"   Objectivetype_Id," +
										"   Expectstarttime," +
										"   Expectendtime," +
										"   Obstatus," +
										"   Recordstatus," +
										"   Attempt," +
										"   Max_Attempt," +
										"   Handleby_Id," +
										"   Handlegroup_Id," +
										"   Createdby," +
										"   Createddate," +
										"   Failure_Attempt," +
										"   Comments," +
										"   Customer_Guid," +
										"   Localtrycount," +
										"   Lastassigndate," +
										"   Workorderframe_Id," +
										"   Curstepstatus," +
										"   Curstep_Id," +
										"   Stepforecastdate," +
										"   Curstep_Id_Map," +
										"   Map_Id," +
										"   Objectivesubstatus," +
										"   Elitetaskstatus," +
										"   Obflag,Maintaskstep_Id_Map)" +
										"Values" +
										"  ('" + EliteTask_Guid + "'," +
										"   '" + Objective_Guid + "'," +
										"   'RE0TX1'," +
										"   Now()," +
										"   Date_Add(Now(), Interval 3 Day)," +
										"   'OPEN'," +
										"   0," +
										"   1," +
										"   999," +
										"   '" + r_Staff_Id + "'," +
										"   '" + r_Rolegroup_Id + "'," +
										"   'SELITE'," +
										"   Now()," +
										"   999," +
										"   ''," +
										"   '" + Customer_Guid + "'," +
										"   0," +
										"   Now()," +
										"   ''," +
										"   'OPEN'," +
										"   'ONA0KD'," +
										"   Now()," +
										"   'ONA0KD'," +
										"   'MY48ZX'," +
										"   'OPEN'," +
										"   'OPEN'," +
										"   1,'ONA0KD')";
										
										int[] batchSQLResult1 = eliteBean.updateBatch(custTaskDealSQL1, "dataSource");
										log.debug("老客户入库批量处理SQL返回结果："+batchSQLResult1.toString());
									}

						
				}
				reJson = "{\"result\":\"1\",\"message\":"+total+"}";

			}else {
				String msg = GetJV(jsonObject, "msg");
				reJson = "{\"result\":\"-1\",\"message\":\"用户获取失败(" + msg + ")\"}";
			}

		} catch (Exception e) {
			log.error("接口处理异常" + e.getMessage());
			// 失败返回
			reJson = "{\"result\":\"-1\",\"message\":\"接口异常\"}";
		}
		return reJson;
	}


	// 解析Json值
	public static String GetJV(JSONObject inJson, String getKey) {
		String Rev_Value = null;
		try {
			Rev_Value = inJson.getString(getKey);
		} catch (Exception e) {
			try {
				Rev_Value = String.valueOf(inJson.getInt(getKey));
			} catch (Exception e1) {
				try {
					Rev_Value = String.valueOf(inJson.getJSONArray(getKey));
				} catch (Exception e2) {
					try {
						Rev_Value = String.valueOf(inJson.getJSONObject(getKey));
					} catch (Exception e3) {
						Rev_Value = "";
					}
				}
			}
		} finally {
			if (Rev_Value == null || Rev_Value.equals("null") || Rev_Value.length() <= 0) {
				Rev_Value = "";
			} else {
			}
		}
		log.debug("解析-k=" + getKey + " v=" + Rev_Value);
		return Rev_Value;
	}


	// 非空校验isNull
	public static boolean isNull(String value) {

		boolean reFlag = true;
		if (value == "" || value.length() <= 0) {
			reFlag = true;
		} else {
			reFlag = false;
		}
		log.debug(reFlag);
		return reFlag;
	}

	// 非空校验isNullMSG
	public static String isNullMSG(String key, String value) {

		String reResult = "";
		if (value == "" || value.length() <= 0) {
			reResult = key + "必填字段;";
		}
		return reResult;
	}

}
